/*
 * 文件名：PayfeeApplyController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年1月15日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.cap.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.dto.cap.PayfeeApplyDto;
import top.infopub.enums.hr.PostGroupEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.domain.PayfeeApplyDomain;
import top.infopub.mgr.cap.jsonvo.PayfeeApplyJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.LoanFinService;
import top.infopub.mgr.cap.service.PayfeeApplyService;
import top.infopub.mgr.cap.vo.PayfeeApplyVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.MarketManageService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.model.cap.PayfeeApply;
import top.infopub.model.cap.PayfeeApplyInfo;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 融资-付费申请
 * @author wuzhiyang
 * @version 2020年1月15日
 * @see PayfeeApplyController
 * @since
 */
@Controller
@RequestMapping("/payfeeApply")
public class PayfeeApplyController extends GenericFlowController {

    @Autowired
    private PayfeeApplyService payfeeApplyService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private LoanFinService loanFinService;

    @Autowired
    private CapProcessManageService capProcessManageService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private MarketManageService marketManageService;

    /**
     * 融资-付费申请列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        //获取登录人员信息
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        //查询区域公司列表
        List<OrgInfo> orgInfoList = marketManageService.queryOrgInfoByAuthUserId(vo);
        request.setAttribute("orgInfoList", orgInfoList);
        return "cap/lay-payFeeApply-list";
    }

    /**
     * 融资-付费申请列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<PayfeeApplyDomain> queryDataByCondition(PayfeeApplyVo payfeeApplyVo,
                                                         ParamPage paramPage) {
        Page<PayfeeApplyDomain> page = new Page<PayfeeApplyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = payfeeApplyService.selectByDomainWhere(page, payfeeApplyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 保证合同Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        request.setAttribute("id", id);
        PayfeeApply payfeeApply=new PayfeeApply();
        if(StringUtils.isNotEmpty(id)){
          payfeeApply=  payfeeApplyService.selectByPrimaryKey(id);
        }
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");//登录人和审批人一致使用该字段是否显示审核信息
        request.setAttribute("finFlag", "0");//指定财务人员进入审批页面必须填写财务信息
        if (payfeeApply != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), payfeeApply.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), payfeeApply.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(payfeeApply.getProcessId()) && payfeeApply.getProcessId().length() > 10) {
                request.setAttribute("processId", payfeeApply.getProcessId());
                String auditTabFlag = capProcessManageService.checkShowAuditTab(payfeeApply.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), payfeeApply.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                //查询指定财务节点人员ID
                List<String> finUserIdList = capProcessManageService.queryFinanceUserIdByProcessId(payfeeApply.getProcessId(), "-1", PostGroupEnum.FINANCE.getCode());
                if (finUserIdList != null && finUserIdList.size() > 0) {
                    for (String finUserId : finUserIdList) {
                        if (StringUtils.isBlank(finUserId)) continue;
                        if (StringUtils.equals(vo.getId(), finUserId)) {
                            //当前待审批节点=当前登录人，需要编辑财务信息提交
                            request.setAttribute("finFlag", "1");//指定财务人员进入审批页面必须填写财务信息
                        }
                    }
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode", proCode);
        return "cap/lay-FinancingPayment-detail";
    }

    @RequestMapping("/queryDetail")
    @ResponseBody
    public RspVo queryDetail(String id) {
        PayfeeApplyJsonVo jsonVo = payfeeApplyService.queryDetailById(id);
        return RspVo.getSuccessResponse(jsonVo);
    }

    @RequestMapping("/queryOneByProCode")
    @ResponseBody
    public RspVo queryOneByProCode(String proCode) {
        PayfeeApplyDto payFeeDto = payfeeApplyService.queryOneByProCode(proCode);
        return RspVo.getSuccessResponse(payFeeDto);
    }

    /**
     * 编辑
     * @param bodyStr json数据
     * @param submitType 0=保存，1=提交
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        PayfeeApplyJsonVo jsonVo = JSON.parseObject(str, PayfeeApplyJsonVo.class);
        PayfeeApplyDto dto = jsonVo.getPayfeeApplyDto();
        List<PayfeeApplyInfo> info=jsonVo.getInfos();

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(jsonVo.getFileAtt()!=null){
            String[] fileAtt = jsonVo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, dto.getProCode(), file);
                attachmentList.add(attachment);
            }
        }
        RspVo rspVo = payfeeApplyService.edit(dto,info, attachmentList, submitType, vo);
        return rspVo;
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String processId, String status, String auditMsg, PayfeeApply payfeeApply) {
        //融资付费审批
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        List<String> finUserIdList = capProcessManageService.queryFinanceUserIdByProcessId(processId, "-1", PostGroupEnum.FINANCE.getCode());
        if (finUserIdList != null && finUserIdList.size() > 0) {
            for (String finUserId : finUserIdList) {
                if (StringUtils.isBlank(finUserId)) continue;
                if (StringUtils.equals(vo.getId(), finUserId)) {
                    //当前待审批节点=当前登录人，需要编辑财务付款情况
                    if (payfeeApply == null || payfeeApply.getActualPayAmt() == null
                            || payfeeApply.getPaymentDate() == null
                            || StringUtils.isBlank(payfeeApply.getSpecification())) {
                        return RspVo.getFailureResponse(401, "财务付款情况不能为空");
                    }
                    RspVo rspVo = payfeeApplyService.modifyFinInfo(payfeeApply, vo);
                    if (!rspVo.isSuccess()) return rspVo;
                    break;
                }
            }
        }
        capProcessManageService.auditProject(payfeeApply.getId(), processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }



    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "loanFinAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                        + filePath);
                LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD, "上传融资放款附件-文件名:" + filePath
                        + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }






//    /**
//     * 融资-付费申请列表数据
//     * @return
//     */
//    @RequestMapping("/queryMyCheckDataByCondition")
//    @ResponseBody
//    public RspVo<PayfeeApplyDomain> queryMyCheckDataByCondition(PayfeeApplyVo payfeeApplyVo,
//                                                                ParamPage paramPage) {
//        Page<PayfeeApplyDomain> page = new Page<PayfeeApplyDomain>();
//        page.setPageNum(paramPage.getPage());
//        page.setPageSize(paramPage.getLimit());
//        //查询时，结束日期增加一天
//        if (payfeeApplyVo.getEndDate() != null) {
//            payfeeApplyVo.setEndDate(DateUtils.addDays(payfeeApplyVo.getEndDate(), 1));
//        }
//        //查询时，申请付费记录结束日期增加一天
//        if (payfeeApplyVo.getEndPayfeeDate() != null) {
//            payfeeApplyVo.setEndPayfeeDate(DateUtils.addDays(payfeeApplyVo.getEndPayfeeDate(), 1));
//        }
//        //增加addby
//        payfeeApplyVo.setAddBy(SessionUserUtils.getSessionUserId());
//        page = payfeeApplyService.selectMyCheckByDomainWhere(page, payfeeApplyVo);
//        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
//    }
//
//    /**
//     * 融资-付费申请-新增
//     * @return
//     */
//    @RequestMapping("/add")
//    public String toAdd(HttpServletRequest request) {
//        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
//        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
//        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
//        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
//        request.setAttribute("bindOrgId", bindOrgId);
//        request.setAttribute("bindOrgName", bindOrgName);
//        request.setAttribute("bindDeptId", bindDeptId);
//        request.setAttribute("bindDeptName", bindDeptName);
//        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
//        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//        request.setAttribute("staffName", staffInfo.getStaffName());
//        //返回所有融资放款的信息
//        request.setAttribute("allProName", loanFinService.queryAllWithOrg());
//        return "cap/lay-payFeeApply-add";
//    }
//
//    /**
//     * 融资-付费记录-新增
//     */
//    @SuppressWarnings("rawtypes")
//    @RequestMapping("/save")
//    @ResponseBody
//    public RspVo save(PayfeeApplyAssist payfeeApplyAssist) {
//
//        //融资-付费记录处理
//        payfeeApplyAssist.setHrDeptId(payfeeApplyAssist.getHrDeptid());
//        payfeeApplyAssist.setHrOrgId(payfeeApplyAssist.getHrOrgid());
//        payfeeApplyAssist.setStaffName(payfeeApplyAssist.getStaffname());
//        payfeeApplyAssist.setHrStaffApplyId(payfeeApplyAssist.getHrStaffApplyid());
//        String codesAndproCode = payfeeApplyAssist.getCodesAndproCode();
//        String[] split = codesAndproCode.split("\\_");
//        payfeeApplyAssist.setProCode(split[1]);
//        //LoanFin loanFin = loanFinService.selectByProCode(split[1], split[0]);
//        //添加项目名称
//        payfeeApplyAssist.setProName(split[2]);
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//        String id = IdFactory.getUUIDUpper();
//        payfeeApplyAssist.setId(id);
//        payfeeApplyAssist.setAddBy(vo.getId());
//        payfeeApplyAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String code = codeGeneratorConfigService.generatorCode("cap_payfee_apply");
//        payfeeApplyAssist.setCodes(code);
//        // 处理processId
//        payfeeApplyAssist.setProcessId(IdFactory.getUUIDUpper());
//        payfeeApplyAssist.setProcessStatus("1");//审批中
//        payfeeApplyAssist.setUptBy(vo.getId());
//        payfeeApplyAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //付费明细表处理
//        List<PayfeeApplyDetail> payfeeApplyDetails = Lists.newLinkedList();
//        //付费明细表数据处理
//        String[] subItemName = payfeeApplyAssist.getSubItemName();
//        if (subItemName != null && subItemName.length > 0) {
//            for (int i = 0; i < subItemName.length; i++ ) {
//                String itemName = subItemName[i];
//                String accountName = payfeeApplyAssist.getSubAccountName()[i];
//                String accountNo = payfeeApplyAssist.getSubAccountNo()[i];
//                String openBankName = payfeeApplyAssist.getSubOpenBankName()[i];
//                String paySingle = payfeeApplyAssist.getSubPaySingle()[i];
//                if (StringUtils.isEmpty(itemName) && StringUtils.isEmpty(itemName)) {
//                    continue;
//                }
//                PayfeeApplyDetail payfeeApplyDetail = new PayfeeApplyDetail();
//                String payfeeApplyDetailId = IdFactory.getUUIDUpper();//自动生成主键
//                payfeeApplyDetail.setId(payfeeApplyDetailId);
//                payfeeApplyDetail.setApplyId(id);
//                payfeeApplyDetail.setAccountName(accountName);
//                payfeeApplyDetail.setAccountNo(accountNo);
//                payfeeApplyDetail.setItemName(itemName);
//                payfeeApplyDetail.setOpenBankName(openBankName);
//                payfeeApplyDetail.setPaySingle(new BigDecimal(paySingle));
//                payfeeApplyDetail.setAddBy(vo.getId());
//                payfeeApplyDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                payfeeApplyDetails.add(payfeeApplyDetail);
//            }
//
//        }
//
//        //上传附件
//        //1=贷款合同
//        List<PayfeeApplyAtt> payfeeApplyAtts = new ArrayList<PayfeeApplyAtt>();
//        String[] fileAtt1 = payfeeApplyAssist.getFileAtt1();
//        if (fileAtt1 != null) {
//            for (String file : fileAtt1) {
//                PayfeeApplyAtt payfeeApplyAtt = createFileAtt(vo, id, file);
//                payfeeApplyAtt.setTypes("1");
//                payfeeApplyAtts.add(payfeeApplyAtt);
//            }
//        }
//        //2=还本付息表
//        String[] fileAtt2 = payfeeApplyAssist.getFileAtt2();
//        if (fileAtt2 != null) {
//            for (String file : fileAtt2) {
//                PayfeeApplyAtt payfeeApplyAtt = createFileAtt(vo, id, file);
//                payfeeApplyAtt.setTypes("2");
//                payfeeApplyAtts.add(payfeeApplyAtt);
//            }
//        }
//        //9=其他材料
//        String[] fileAtt9 = payfeeApplyAssist.getFileAtt9();
//        if (fileAtt9 != null) {
//            for (String file : fileAtt9) {
//                PayfeeApplyAtt payfeeApplyAtt = createFileAtt(vo, id, file);
//                payfeeApplyAtt.setTypes("9");
//                payfeeApplyAtts.add(payfeeApplyAtt);
//            }
//        }
//        payfeeApplyService.savePayfeeApply(payfeeApplyAssist, payfeeApplyDetails, payfeeApplyAtts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "融资管理 -新增融资-付费记录：项目名="
//                                                              + payfeeApplyAssist.getProName(),
//            null);
//        return RspVo.getSuccessResponse();
//    }
//
//    private PayfeeApplyAtt createFileAtt(AuthorizationVO vo, String applyId, String file) {
//        //资料信息数组
//        String[] fileAttStr = file.split("\\|");
//        PayfeeApplyAtt fileAtt = new PayfeeApplyAtt();
//        fileAtt.setId(IdFactory.getUUIDUpper());
//        fileAtt.setApplyId(applyId);//付费申请id
//        //fileAtt.setTypes(fileAttStr[0].substring(0, 1));//附件类型 1=贷款合同 2=还本付息表 9=其他材料
//        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
//        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
//            fileAttStr[1].length()).toLowerCase();//后缀转小写
//        fileAtt.setFileName(fileName);//文件名
//        fileAtt.setFileSuffix(suffix);//文件后缀
//        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
//        fileAtt.setAddBy(vo.getId());//添加人
//        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
//        return fileAtt;
//    }
//
//    /**
//     * 上传附件
//     * @param request
//     * @param response
//     * @return
//     * @throws IOException
//     * @see
//     */
//    @SuppressWarnings("rawtypes")
//    @RequestMapping("/uploadAtt")
//    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
//        throws IOException {
//        List<String> returnFileStrList = new ArrayList<>();
//        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
//        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
//        if (map != null) {
//            for (String name : map.keySet()) {
//                MultipartFile file = map.get(name);
//                //资料类型
//                String types = request.getParameter("types");
//                if (StringUtils.isEmpty(types)) {
//                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
//                }
//                // 上传文件
//                String fileId = IdFactory.getUUIDSerialNumber();
//                // 服务器资源路径
//                String serverPath = "payFeeApplyAtt";
//                String filePath = FileHelper.upload(file, serverPath);
//                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
//                                      + fileId + "|" + filePath);
//                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传融资合同附件-文件名:" + filePath
//                                                                      + "，文件路径:" + filePath, null);
//            }
//        }
//        return RspVo.getSuccessResponse(returnFileStrList);
//    }
//
//    /**
//     * 根据id查询融资-付费记录详情  > 注意：方法命名必须为：toDealOrDetail
//     * @param id 融资-付费记录Id
//     * @return
//     * @see
//     */
//    @RequestMapping("/toDealOrDetail")
//    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        PayfeeApplyVo payfeeApplyVo = payfeeApplyService.selectById(id);
//        PayfeeApplyVo applyVo = payfeeApplyService.selectByGuid(id);
//        payfeeApplyVo.setCompName(applyVo.getCompName());
//        request.setAttribute("modelDetail", payfeeApplyVo);
//        map.put("payfeeApplyVo", payfeeApplyVo);
//        // 审批flag
//        request.setAttribute("processDealWith", processDealWith);
//        // 审批data
//        processData(request, payfeeApplyVo.getProcessId());
//        return new ModelAndView("cap/lay-payFeeApply-detail", map);
//    }
//
//    /**
//     * 根据id查询付款公司信息(带出的)
//     * @param id 项目Id
//     * @return
//     * @see
//     */
//    @RequestMapping("/getOrgInfoAllByProCode")
//    @ResponseBody
//    public Map<String, Object> getOrgInfoAllByProCode(String codesAndproCode) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        String[] split = codesAndproCode.split("\\_");
//        String proCode = split[1];
//        try {
//            OrgInfo orgInfo = orgInfoService.queryByProjectCode(proCode);
//            map.put("orgInfo", orgInfo);
//        }
//        catch (Exception e) {
//            log.error("根据单据ID获取付款公司信息异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }
//
//    /**
//     * 融资付款申请-复制单据
//     * @return
//     */
//    @RequestMapping("/toCopy")
//    public String toCopy(HttpServletRequest request) {
//        String id = request.getParameter("id");
//        PayfeeApplyVo payfeeApplyVo = payfeeApplyService.selectById(id);
//        PayfeeApplyVo applyVo = payfeeApplyService.selectByGuid(id);
//        payfeeApplyVo.setCompName(applyVo.getCompName());
//        request.setAttribute("payfeeApplyVo", payfeeApplyVo);
//        return "cap/lay-payFeeApply-copy";
//    }

}
